package net.sudot.flow.api;

import net.sudot.flow.utils.GroovyExecuteUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tangjialin on 2020/2/19.
 */
@RestController
public class TestController {
    Logger log = LoggerFactory.getLogger(getClass());
    private RestTemplate restTemplate = new RestTemplate();

    /**
     * Gradle示例
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/gradle")
    @ResponseBody
    public Object gradle() throws Exception {
        String baseDir = ClassLoader.getSystemResource("transform/").getPath();
        return GroovyExecuteUtils.execute(baseDir, "DemoDSL.groovy", null);
    }

    //    @PostMapping("/{channel}/{interfaceName}")
    @RequestMapping("/{channel}/{interfaceName}")
    @ResponseBody
    public Object request(@PathVariable String channel, @PathVariable String interfaceName,
                          @RequestBody(required = false) Map<String, Object> data) throws Exception {
        String scriptPath = channel + "/" + interfaceName;
        log.info("[开始执行交互,接口编号={},参数={}]", scriptPath, data);
        String baseDir = ClassLoader.getSystemResource("transform/").getPath();
        Map<Object, Object> variables = new HashMap<>(2);
        variables.put("scriptPath", scriptPath);
        variables.put("inputData", data == null ? new HashMap<>(0) : data);
        variables.put("restTemplate", restTemplate);
        return GroovyExecuteUtils.execute(baseDir, "Entrance.groovy", variables);
    }

    /**
     * 模拟接口
     *
     * @param data 请求数据
     * @return 响应数据
     */
    @PostMapping("/mock")
    @ResponseBody
    public Object mock(@RequestBody(required = false) Map<String, Object> data) {
        return data;
    }
}